<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户姓名" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择用户" style="width: 200px;" @keyup.enter="handleQuery">
          <el-option v-for="user in usersList" :key="user.id" :label="user.userName" :value="user.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="兑换积分" prop="exchangeValue">
        <el-input v-model="queryParams.exchangeValue" placeholder="请输入兑换积分" clearable @keyup.enter="handleQuery" style="width:200px;"/>
      </el-form-item>
      <el-form-item label="服务类型" prop="exchangeGid">
        <el-select v-model="queryParams.exchangeGid" placeholder="请选择服务类型" style="width: 200px;"
          @keyup.enter="handleQuery">
          <el-option v-for="service_type in service_typeList" :key="service_type.id" :label="service_type.name"
            :value="service_type.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="兑换时间" prop="exchangeTime">
        <el-date-picker clearable v-model="queryParams.exchangeTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择兑换时间" style="width:200px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['chy:integralexchange:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['chy:integralexchange:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['chy:integralexchange:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['chy:integralexchange:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="integralexchangeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="兑换编号" align="center" prop="id" />
      <el-table-column label="用户姓名" align="center">
        <template #default="scope">
          {{ getUserNameById(scope.row.userId) }}
        </template>
      </el-table-column>
      <el-table-column label="兑换积分" align="center" prop="exchangeValue" />
      <el-table-column label="服务类型" align="center" prop="exchangeGid">
        <template #default="scope">
          <el-tag :type="getTagType(scope.row.exchangeGid)">
            {{ getServiceNameById(scope.row.exchangeGid) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="兑换时间" align="center" prop="exchangeTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.exchangeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['chy:integralexchange:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['chy:integralexchange:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改积分兑换对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="integralexchangeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户姓名" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户">
            <el-option v-for="user in usersList" :key="user.id" :label="user.userName" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="兑换积分" prop="exchangeValue">
          <el-input v-model="form.exchangeValue" placeholder="请输入兑换积分" />
        </el-form-item>
        <el-form-item label="服务类型" prop="exchangeGid">
          <el-select v-model="form.exchangeGid" placeholder="请选择服务类型">
            <el-option v-for="service_type in service_typeList" :key="service_type.id" :label="service_type.name"
              :value="service_type.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="兑换时间" prop="exchangeTime">
          <el-date-picker clearable v-model="form.exchangeTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择兑换时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Integralexchange">
import { listIntegralexchange, getIntegralexchange, delIntegralexchange, addIntegralexchange, updateIntegralexchange } from "@/api/chy/integralexchange"
import { listUsers } from "@/api/gas/users"
import { listService_type } from "@/api/chy/service_type"

const { proxy } = getCurrentInstance()

const integralexchangeList = ref([])
const service_typeList = ref([])
const usersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    exchangeValue: null,
    exchangeGid: null,
    exchangeTime: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)
/**
 * 根据服务类型 ID 获取对应的标签类型
 * @param {number} exchangeGid - 服务类型 ID
 * @returns {string} 标签类型
 */
 function getTagType(exchangeGid) {
  // 这里可以根据实际的服务类型 ID 来映射不同的标签类型
  // 示例：假设服务类型 ID 为 1 是 'success'，2 是 'warning'，其他是 'info'
  switch (exchangeGid) {
    case 1:
      return 'success';
    case 2:
      return 'warning';
    case 3:
      return 'danger';
    case 4:
      return 'success';
    case 5:
      return 'primary';
    default:
      return 'info';
  }
}
/** 查询积分兑换列表 */
function getList() {
  loading.value = true
  listIntegralexchange(queryParams.value).then(response => {
    integralexchangeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getListUsers() {
  loading.value = true
  queryParams.value.params = {}
  listUsers(queryParams.value).then(response => {
    usersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function getUserNameById(userId) {
  const user = usersList.value.find(user => user.id == userId)
  return user ? user.userName : '未知用户'
}
function getListServiceType() {
  loading.value = true
  listService_type(queryParams.value).then(response => {
    service_typeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getServiceNameById(exchangeGid) {
  const serviceType = service_typeList.value.find(serviceType => serviceType.id == exchangeGid)
  return serviceType ? serviceType.name : '未知服务'
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    exchangeValue: null,
    exchangeGid: null,
    exchangeTime: null
  }
  proxy.resetForm("integralexchangeRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加积分兑换"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getIntegralexchange(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改积分兑换"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["integralexchangeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateIntegralexchange(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addIntegralexchange(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除积分兑换编号为"' + _ids + '"的数据项？').then(function () {
    return delIntegralexchange(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('chy/integralexchange/export', {
    ...queryParams.value
  }, `integralexchange_${new Date().getTime()}.xlsx`)
}

getList()
getListUsers()
getListServiceType()
</script>
